###
#
# COVID-19 Narrative Project
#
# This code is used for the calculations and visualizations presented in the
# paper, "Interpreting crises through narratives: the construction of a COVID-19 
# policy narrative by Canada’s political parties" in Critical Policy Studies
#
# 
# Tyler Girard
# University of Western Ontario
# Email: tgirard2@uwo.ca
#
# 
#
###

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Set up HERE ####

library(here)
here()

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Load Packages ####

library(tidyverse)
library(splitstackshape)
library(rio)

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Extra Functions ####

roles <- function(x) sub("[^_]*_", "", x ) 

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Load Data ####

df <- import(here("Data", "Policy Narrative Framework Analysis_Replication Data.xlsx"))

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Set Seed ####

set.seed(155)

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### Summary Stats ####

# total number of statements by party
df_tots <- df %>%
  group_by(Party) %>%
  summarise(nstatements = n())

# length of statements
dfsum <- df %>%
  mutate(nw = stringi::stri_count_words(Text)) %>%
  summarize(av = mean(nw), lwr = min(nw), upr = max(nw), s = sd(nw))

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### 1 Crisis Setting ####

crisis <- df %>%
  select(Party, Crisis_Health, Crisis_Econ, Crisis_Social) %>%
  group_by(Party) %>%
  summarise(healthtot = sum(Crisis_Health),
            econtot = sum(Crisis_Econ),
            socialtot = sum(Crisis_Social)) 

crisis_tab <- crisis %>%
  left_join(df_tots) %>%
  mutate(prophealth = paste0(round(healthtot/nstatements * 100), "%"),
         propecon = paste0(round(econtot/nstatements * 100), "%"),
         propsocial = paste0(round(socialtot/nstatements * 100), "%")) %>%
  select(Party, healthtot, prophealth, econtot, propecon, socialtot, propsocial) %>%
  filter(Party != "GP")

crisis_tab

write.csv(crisis_tab, file = here("Tables", "Table_Narrative Setting.csv"))


#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### 2 Villains/Perpetrators ####

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Summary Table ~ ####

VillainPerp <- df %>%
  select(c(ID:Type, VillainPerp)) %>%
  filter(Party != "GP") %>%
  drop_na(VillainPerp) %>%
  mutate(VillainPerp = trimws(VillainPerp),
         VillainPerp = tolower(VillainPerp),
         VillainPerp = str_remove(VillainPerp, "sector"))

VillainPerp_tots <- VillainPerp %>%
  group_by(Party) %>%
  count() %>%
  left_join(df_tots) %>%
  mutate(props = n/nstatements,
         category = "Villain/Perps")


VillainPerp <- cSplit(data.frame(VillainPerp), 'VillainPerp', ";")


VillainPerp2 <- VillainPerp %>%
  pivot_longer(cols = c(VillainPerp_1:VillainPerp_3))

VillainPerp2 <- cSplit(data.frame(VillainPerp2), 'value', "_") %>%
  rename(level1 = value_1,
         level2 = value_2)


VillainPerp_wc1 <- VillainPerp2 %>%
  drop_na(level1) %>%
  group_by(Party) %>%
  count(level1)


villainperp_comptots <- data.frame(
  Party = rep(c("BQ","CPC","Liberal","NDP"), each = 6),
  level1 = rep(c("actions or policies","business","canadian actors","covid-19","foreign actors","government"), times = 4)
)

villainperp_comptots <- villainperp_comptots %>%
  left_join(VillainPerp_wc1) %>%
  replace_na(list(n = 0)) %>%
  mutate(n_total = ifelse(Party == "BQ", df_tots$nstatements[df_tots$Party == "BQ"],
                          ifelse(Party == "CPC", df_tots$nstatements[df_tots$Party == "CPC"],
                                 ifelse(Party == "Liberal", df_tots$nstatements[df_tots$Party == "Liberal"],
                                        ifelse(Party == "NDP", df_tots$nstatements[df_tots$Party == "NDP"], 0))))) %>%
  mutate(n_villain = ifelse(Party == "BQ", VillainPerp_tots$n[VillainPerp_tots$Party == "BQ"],
                            ifelse(Party == "CPC", VillainPerp_tots$n[VillainPerp_tots$Party == "CPC"],
                                   ifelse(Party == "Liberal", VillainPerp_tots$n[VillainPerp_tots$Party == "Liberal"],
                                          ifelse(Party == "NDP", VillainPerp_tots$n[VillainPerp_tots$Party == "NDP"], 0))))) %>%
  mutate(prop_villain = round(n / n_villain * 100)) %>%
  mutate(prop_total = round(n / n_total * 100)) %>%
  select(c(Party, level1, n, prop_villain, prop_total)) %>%
  mutate(prop_villain = paste0(prop_villain, "%")) %>%
  mutate(prop_total = paste0(prop_total, "%"))

villainperp_comptots

write.csv(villainperp_comptots, file = here("Tables", "Table_Villain Level 1 Totals.csv"))

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Sub-Topic Figure ~ ####

VillainPerp_wc2 <- VillainPerp2 %>%
  drop_na(level2) %>%
  group_by(Party) %>%
  count(level2) %>%
  arrange(Party, desc(n)) %>%
  group_by(Party) %>% 
  mutate(id = 1:n()) %>%
  filter(id < 6)


villains_lvl2_bar <- ggplot(cbind(VillainPerp_wc2, new=paste(VillainPerp_wc2$Party, VillainPerp_wc2$level2,sep = "_")), 
                            aes(x = reorder(new,n), y = n, fill = Party, label = n)) +
  geom_bar(stat= "identity", color = "black") +
  facet_wrap(~Party, ncol = 1, scales = "free_x") +
  scale_fill_manual(values = c("#33B2CC","#002FA1","#D71920","#F37021")) +
  scale_y_continuous(limits = c(0, 85)) +
  scale_x_discrete(labels=roles) +
  geom_text(position = position_dodge(width = .9),    # move to center of bars
            vjust = -0.5,    # nudge above top of bar
            size = 3) +
  theme_bw() +
  theme(
    strip.background = element_rect(fill = "#EBECF0"),
    strip.text = element_text(face = "bold"),
    legend.position = "none"
  ) +
  labs(
    #title = "Identifying 'Villains' of the Crisis",
    #subtitle = "Top 5 Sub-Topic Codes by Party",
    x = "Sub-Topic Code",
    y = "Number of Statements with Sub-Topic Code"
  )

ggsave(villains_lvl2_bar, filename = here("Figures", "Villains_Top 5 Sub-Topic Codes by Party.png"), height = 4, width = 6)


#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### 3 Victims ####

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Summary Table ~ ####

victims <- df %>%
  select(c(ID:Type, Victim)) %>%
  filter(Party != "GP") %>%
  drop_na(Victim) %>%
  mutate(Victim = trimws(Victim),
         Victim = tolower(Victim))

victims_tots <- victims %>%
  group_by(Party) %>%
  count() %>%
  left_join(df_tots) %>%
  mutate(props = n/nstatements,
         category = "Victim")


victims <- cSplit(data.frame(victims), 'Victim', ";")


victest <- victims %>%
  pivot_longer(cols = c(Victim_01:Victim_10))

victest <- cSplit(data.frame(victest), 'value', "_") %>%
  rename(level1 = value_1,
         level2 = value_2)


victims_wc1 <- victest %>%
  drop_na(level1) %>%
  group_by(Party) %>%
  count(level1)



victim_comptots <- data.frame(
  Party = rep(c("BQ","CPC","Liberal","NDP"), each = 7),
  level1 = rep(c("business", "canadians", "covid-19", "economic sector", "government", "social group", "workers"), times = 4)
)

victim_comptots <- victim_comptots %>%
  left_join(victims_wc1) %>%
  replace_na(list(n = 0)) %>%
  mutate(n_total = ifelse(Party == "BQ", df_tots$nstatements[df_tots$Party == "BQ"],
                          ifelse(Party == "CPC", df_tots$nstatements[df_tots$Party == "CPC"],
                                 ifelse(Party == "Liberal", df_tots$nstatements[df_tots$Party == "Liberal"],
                                        ifelse(Party == "NDP", df_tots$nstatements[df_tots$Party == "NDP"], 0))))) %>%
  mutate(n_victim = ifelse(Party == "BQ", victims_tots$n[victims_tots$Party == "BQ"],
                           ifelse(Party == "CPC", victims_tots$n[victims_tots$Party == "CPC"],
                                  ifelse(Party == "Liberal", victims_tots$n[victims_tots$Party == "Liberal"],
                                         ifelse(Party == "NDP", victims_tots$n[victims_tots$Party == "NDP"], 0))))) %>%
  mutate(prop_victim = round(n / n_victim * 100)) %>%
  mutate(prop_total = round(n / n_total * 100)) %>%
  select(c(Party, level1, n, prop_victim, prop_total)) %>%
  mutate(prop_victim = paste0(prop_victim, "%")) %>%
  mutate(prop_total = paste0(prop_total, "%"))

victim_comptots

write.csv(victim_comptots, file = here("Tables", "Table_Victims Level 1 Totals.csv"))

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Sub-Topic Figure ~ ####

victims_wc2 <- victest %>%
  drop_na(level2) %>%
  group_by(Party) %>%
  count(level2) %>%
  arrange(Party, desc(n)) %>%
  group_by(Party) %>% 
  mutate(id = 1:n()) %>%
  filter(id < 11)

victims_wc2$level2 <- gsub("and", "&", victims_wc2$level2)
victims_wc2$level2 <- gsub("hospitality & tourism", "H & T", victims_wc2$level2)
victims_wc2$level2 <- gsub("arts & entertainment", "A & E", victims_wc2$level2)


victim_lvl2_bar <- ggplot(cbind(victims_wc2, new=paste(victims_wc2$Party, victims_wc2$level2,sep = "_")), 
                          aes(x = reorder(new,n), y = n, fill = Party, label = n)) +
  geom_bar(stat= "identity", color = "black") +
  facet_wrap(~Party, ncol = 1, scales = "free_x") +
  scale_fill_manual(values = c("#33B2CC","#002FA1","#D71920","#F37021")) +
  scale_y_continuous(limits = c(0, 40)) +
  scale_x_discrete(labels=roles) +
  geom_text(position = position_dodge(width = .9),    # move to center of bars
            vjust = -0.5,    # nudge above top of bar
            size = 3) +
  theme_bw() +
  theme(
    #axis.text.x = element_text(angle = 45, vjust = 3),
    axis.text = element_text(size = 8),
    strip.background = element_rect(fill = "#EBECF0"),
    strip.text = element_text(face = "bold"),
    legend.position = "none"
  ) +
  labs(
    #title = "Identifying 'Victims' of the Crisis",
    #subtitle = "Top 10 Sub-Topic Codes by Party",
    x = "Sub-Topic Code",
    y = "Number of Statements with Sub-Topic Code"
  )

victim_lvl2_bar

ggsave(victim_lvl2_bar, filename = here("Figures", "Victims_Top 10 Sub-Topic Codes by Party.png"), height = 4, width = 6)


#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### 4 Heroes/Allies ####

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Summary Table ~ ####

HeroAllies <- df %>%
  select(c(ID:Type, HeroAllies)) %>%
  filter(Party != "GP") %>%
  drop_na(HeroAllies) %>%
  mutate(HeroAllies = trimws(HeroAllies),
         HeroAllies = tolower(HeroAllies),
         HeroAllies = str_remove(HeroAllies, "sector"))

HeroAllies_tots <- HeroAllies %>%
  group_by(Party) %>%
  count() %>%
  left_join(df_tots) %>%
  mutate(props = n/nstatements,
         category = "Hero/Allies")


heroes <- cSplit(data.frame(HeroAllies), 'HeroAllies', ";")


heroes <- heroes %>%
  pivot_longer(cols = c(HeroAllies_1:HeroAllies_6))

heroes <- cSplit(data.frame(heroes), 'value', "_") %>%
  rename(level1 = value_1,
         level2 = value_2)


heroes_wc1 <- heroes %>%
  drop_na(level1) %>%
  group_by(Party) %>%
  count(level1)


heroes_comptots <- data.frame(
  Party = rep(c("BQ","CPC","Liberal","NDP"), each = 8),
  level1 = rep(c("business", "canadians", "domestic actors", "government", "political", "workers", "foreign actors", "science"), times = 4)
)

heroes_comptots <- heroes_comptots %>%
  left_join(heroes_wc1) %>%
  replace_na(list(n = 0)) %>%
  mutate(n_total = ifelse(Party == "BQ", df_tots$nstatements[df_tots$Party == "BQ"],
                          ifelse(Party == "CPC", df_tots$nstatements[df_tots$Party == "CPC"],
                                 ifelse(Party == "Liberal", df_tots$nstatements[df_tots$Party == "Liberal"],
                                        ifelse(Party == "NDP", df_tots$nstatements[df_tots$Party == "NDP"], 0))))) %>%
  mutate(n_hero = ifelse(Party == "BQ", HeroAllies_tots$n[HeroAllies_tots$Party == "BQ"],
                         ifelse(Party == "CPC", HeroAllies_tots$n[HeroAllies_tots$Party == "CPC"],
                                ifelse(Party == "Liberal", HeroAllies_tots$n[HeroAllies_tots$Party == "Liberal"],
                                       ifelse(Party == "NDP", HeroAllies_tots$n[HeroAllies_tots$Party == "NDP"], 0))))) %>%
  mutate(prop_hero = round(n / n_hero * 100)) %>%
  mutate(prop_total = round(n / n_total * 100)) %>%
  select(c(Party, level1, n, prop_hero, prop_total)) %>%
  mutate(prop_hero = paste0(prop_hero, "%")) %>%
  mutate(prop_total = paste0(prop_total, "%"))

heroes_comptots

write.csv(heroes_comptots, file = here("Tables", "Table_Heroes Level 1 Totals.csv"))


#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### ~ Sub-Topic Figure ~ ####

heroes_wc2 <- heroes %>%
  drop_na(level2) %>%
  group_by(Party) %>%
  count(level2) %>%
  arrange(Party, desc(n)) %>%
  group_by(Party) %>% 
  mutate(id = 1:n()) %>%
  filter(id < 11)

heroes_lvl2_bar <- ggplot(cbind(heroes_wc2, new=paste(heroes_wc2$Party, heroes_wc2$level2,sep = "_")), 
                          aes(x = reorder(new,n), y = n, fill = Party, label = n)) +
  geom_bar(stat= "identity", color = "black") +
  facet_wrap(~Party, ncol = 1, scales = "free_x") +
  scale_fill_manual(values = c("#33B2CC","#002FA1","#D71920","#F37021")) +
  scale_y_continuous(limits = c(0, 240), breaks = c(0,50,100,150,200)) +
  scale_x_discrete(labels=roles) +
  geom_text(position = position_dodge(width = .9),    # move to center of bars
            vjust = -0.5,    # nudge above top of bar
            size = 3) +
  theme_bw() +
  theme(
    axis.text = element_text(size = 7),
    strip.background = element_rect(fill = "#EBECF0"),
    strip.text = element_text(face = "bold"),
    legend.position = "none"
  ) +
  labs(
    #title = "Identifying 'Heroes/Allies' of the Crisis",
    #subtitle = "Top 10 Sub-Topic Codes by Party",
    x = "Sub-Topic Code",
    y = "Number of Statements with Sub-Topic Code"
  )

heroes_lvl2_bar

ggsave(heroes_lvl2_bar, filename = here("Figures", "Heroes_Top 10 Sub-Topic Codes by Party.png"), height = 4, width = 6)


#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#

#### End of Script ####

#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
#-----------------------------------------------------------------------------------------------------------------------------------------------------------#
